package com.wanfajie.smsdistribute.db

import android.util.Log
import kotlin.reflect.KClass

fun <R, E: KClass<out Exception>> quietInvoke(
        tag: String = "quietInvoke",
        vararg ignores: E,
        callback: (Exception) -> Unit = { e -> Log.e(tag, e.message, e)},
        func: () -> R) : R? {

    var result: R? = null

    try {
        result = func.invoke()
    } catch (e: Exception) {
        if (!ignores.contains(e::class)) {
            throw e
        }

        callback.invoke(e)
    }

    return result
}

fun <R, E: KClass<out Exception>> quietInvoke(
        tag: String = "quietInvoke",
        default: R,
        vararg ignores: E,
        callback: (Exception) -> Unit = { e -> Log.e(tag, e.message, e)},
        func: () -> R) : R {

    val result: R

    result = try {
        func.invoke()
    } catch (e: Exception) {

        if (!ignores.contains(e::class)) {
            throw e
        }
        callback.invoke(e)
        default
    }

    return result
}
